import env from "@/config/env";
import { FileType } from "@/typings/enums";
import Axios from "axios";
// import store from "@/store";

/**
 * 文件预览url拼接
 * @param {string} fileName 文件名
 * @param {string} storagePath 文件url地址
 * @return {string}
 *
 */
export function filePreview(fileName: string, storagePath: string): string {
  if (
    fileName.split(".")[1] === "png" ||
    fileName.split(".")[1] === "jpg" ||
    // fileName.split(".")[1] === "pdf" ||
    fileName.split(".")[1] === "gif" ||
    fileName.split(".")[1] === "jpeg" ||
    fileName.split(".")[1] === "bmp"
  ) {
    return storagePath;
  } else {
    let userInfo: any = sessionStorage.getItem("userInfo")?.toString();
    userInfo = userInfo ? JSON.parse(userInfo) : {};

    const date = new Date();
    const fullDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
    const preString = "上海同济工程咨询有限公司版权所有-" + userInfo.user.nickName;
    const _return = `${env.previewUrl}/view/url?url=${encodeURIComponent(storagePath)}&watermark=${preString}-${fullDate}&name=${encodeURIComponent(fileName)}`;
    return _return;
  }
}

/**
 * 文件显示单位
 * @param {number} bytes 文件字节长度
 */
export function bytesToSize(bytes: number) {
  if (bytes === 0) return "0 B";
  const k = 1024,
    sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
    i = Math.floor(Math.log(bytes) / Math.log(k));

  return (bytes / Math.pow(k, i)).toFixed(2) + " " + sizes[i];
}

/**
 * 通过文件名，返回文件icon
 * @param {number} suffix 文件后缀
 * @return {string} 如：doc,txt...没有获取到后缀名返回空字符串
 */
export function getFileIcon(suffix: string): string {
  const icons: any = FileType;
  if (icons[suffix]) {
    return icons[suffix];
  } else {
    return icons["default"];
  }
}

/**
 * 手机格式验证
 * @param {string} mobile 手机号码
 * @return {boolean}
 */
export function checkPhone(mobile: string) {
  if (!/^1[3456789]\d{9}$/.test(mobile)) {
    return false;
  }
  return true;
}

/**
 * 跳转到登陆页, 并处理一些逻辑
 */
export function goLoginPage(params?: Common.GoLoginParams) {
  // console.log(store);
  // store.dispatch("User/setUser", null);
  // debugger;
  if (!/\/login(\?|)/.test(location.href)) {
    const uri = encodeURIComponent(location.href);

    localStorage.removeItem("token");
    sessionStorage.removeItem("userInfo");
    let _params = "";
    if (params) {
      const keys = Object.keys(params);
      for (const key of keys) {
        _params = `&${key}=${params[key]}`;
      }
    }
    setTimeout(() => {
      const url = `/#/login?return=${uri}${_params}`;
      location.replace(url);
    });
  }
}

/**
 * 防止open方法被浏览器阻止，所以生成a标签，进行跳转
 * @param {string} url 跳转地址
 * @param {string} target 设置a标签的target值，默认_blank
 */
export function cOpen({ url = "", target = "_blank", download = false } = {}) {
  const a = document.createElement("a");
  a.setAttribute("href", url);
  if (target) {
    a.setAttribute("target", target);
  }
  if (download) {
    a.setAttribute("download", "dd");
  }
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

/**
 * 插件安装检查机制
 * @param where
 */
export function checkShortUrl(where: any) {
  setTimeout(async function() {
    const res = await where.$api.hasShortUrl();
    console.log("2:执行完毕" + res.data);
    if (res && res.code === 200 && res.data === true) {
      alert("请下载安装插件，或同意跳转");
    }
  }, 5000);
}

export function cOpenIE(where: any, url: string) {
  const that = where;
  const a = document.createElement("a");
  a.setAttribute("href", "openIE:" + url);
  a.click();
  console.log("1：执行完毕");
  checkShortUrl(that);
}

/**
 * 设置cookie, 默认30天有效期
 * @param name
 * @param value
 * @param {number} time 秒
 */
export function setCookie(name: string, value: string, time: number) {
  if (!time || time < 0) {
    time = 30 * 24 * 60 * 60;
  }
  const exp = new Date();
  exp.setTime(exp.getTime() + time * 1000);
  document.cookie = name + "=" + escape(value) + ";expires=" + exp.toUTCString();
}

/**
 * 读取cookies
 * @param name
 */
export function getCookie(name: string) {
  let arr;
  const reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if ((arr = document.cookie.match(reg))) return unescape(arr[2]);
  else return null;
}

/**
 * 删除cookies
 * @param name
 */
export function delCookie(name: string) {
  const exp = new Date();
  const cval = getCookie(name);

  exp.setTime(exp.getTime() - 1);
  if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toUTCString();
}

/**
 * 检测系统是否能唤起IE浏览器
 * protocolCheck方法由protocolCheck.js提供
 * @param prefix 自定义协议字符串
 * @param url 跳转链接
 */
export function protocolCheck(prefix = "", url: string) {
  return new Promise((resolve: any) => {
    (window as any).protocolCheck(
      `${prefix + url}`,
      function() {
        resolve(false);
      },
      function() {
        resolve(true);
      }
    );
  });
}

/**
 * 检测浏览器是否是360
 */
export function is360() {
  let _return = false;
  if (navigator && navigator.mimeTypes && navigator.mimeTypes.length) {
    // application/x-mplayer2
    for (const item of navigator.mimeTypes) {
      if (item.type === "application/x-mplayer2") {
        _return = true;
        break;
      }
    }
  }
  return _return;
}

/**
 * 文件下载
 * @param url
 * @returns
 */
export function funDownload({ fileName = "", url = "" }) {
  Axios({ url, responseType: "blob" }).then((res) => {
    // 创建隐藏的可下载链接
    let eleLink: any = document.createElement("a");
    eleLink.download = fileName;
    eleLink.style.display = "none";
    // 字符内容转变成blob地址
    const blob = new Blob([res.data]);
    eleLink.href = URL.createObjectURL(blob);
    // 触发点击
    // document.body.appendChild(eleLink);
    eleLink.click();
    eleLink = null;
    // 然后移除;
    // document.body.removeChild(eleLink);
  });
}
